<script setup lang="ts">
import { promptList } from '~/logic'

const selectValue = ref('')

// 这里整理了输入值的问题
function selectPrompt(item: any) {
  selectValue.value = item.id
  const textarea = document?.querySelector('#prompt-textarea')
  const value = textarea!.value || ''
  // 这里获取值
  nextTick(() => {
    // 这里会根据prompt结构进行处理, 清空的时候
    const text = item.prompt.split(/>>>.*?<<</g).join(`\n${value}`)
    textarea!.value = text
    const event = new Event('input', {
      bubbles: true,
      cancelable: true,
    })
    textarea!.dispatchEvent(event)
    // 延迟执行focus方法
    setTimeout(() => {
      textarea!.focus()
      textarea!.selectionStart = textarea!.selectionEnd = textarea!.value.length
    }, 100)
  })
}

function clear() {
  selectValue.value = ''
  const textarea = document?.querySelector('#prompt-textarea')
  nextTick(() => {
    textarea!.value = ''
    const event = new Event('input', {
      bubbles: true,
      cancelable: true,
    })
    textarea!.dispatchEvent(event)
  })
}

function confirm() {
  const inputElement = document.querySelector('#prompt-textarea')
  // 创建一个键盘事件
  const event = new KeyboardEvent('keydown', {
    bubbles: true,
    cancelable: true,
    key: 'Enter',
    shiftKey: false,
  })
  // 触发 input 元素上的键盘事件
  inputElement!.dispatchEvent(event)
}

</script>

<template>
  <ResizableDraggable :left="500" :top="100">
    <div
      class="select-main"
    >
      <div class="prompt-list">
        <template v-for="item in promptList" :key="item.id">
          <div
            v-if="item.status"
            class="prompt-btn"
            :class="[selectValue === item.id ? 'active' : '']"
            @click="selectPrompt(item)"
          >
            {{ item.name }}
          </div>
        </template>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="confirm">
        确定
      </el-button>
      <el-button type="danger" @click="clear">
        清空
      </el-button>
    </template>
  </ResizableDraggable>
</template>

<style scoped>
.prompt-btn {
  width: 100%;
  font-size: 12px;
  box-sizing: border-box;
  padding: 6px;
  border-radius: 6px;
  line-height: 16px;
  text-align: center;
  background: #ffffff;
  margin-bottom: 6px;
  cursor: pointer;
  color: #000;
  border: 1px solid #cfcfcf;
  white-space: break-spaces;
}
.prompt-btn.active {
  background: var(--el-color-primary);
  color: #fff;
}
</style>
